<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button @click="save()" :disabled="!canSave">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-depotName>
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择退出仓库"
                v-model="formInfo.data.depotName"
              >
                <template #append>
                  <el-icon @click="selectDepotExport"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-storeDepotName>
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择退入仓库"
                v-model="formInfo.data.storeDepotName"
              >
                <template #append>
                  <el-icon @click="selectDepotStorage"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->

          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!canAddProduct" @click="addProduct()"
                >添加产品
              </el-button>
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canDeleteProduct" @click="removeProduct()"
                >删除产品
              </el-button>
            </template>

            <template v-slot:filter-scanCode>
              <ScanInputBox
                :query="scanInfo.query"
                :api="scanInfo.api"
                :disabled="!canAddProduct"
                @callback="onCallBackScanData"
              />
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :tabIndex="true"
                :check-box="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <template v-if="!tableInfo.isSysGroup">
                    <el-form-item
                      class="margin-bottom"
                      v-if="
                        scope.row.codeType === 1 || scope.row.codeType === 4
                      "
                    >
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item">
                            <el-form-item
                              :prop="`data.${scope.$index}.largeUnitQty`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: $validate.positiveAndZero,
                                        trigger: 'blur',
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.largeUnitQty"
                                clearable
                                controls-position="right"
                                :precision="
                                  scope.row.qtyOperateMode === 0 ||
                                  scope.row.qtyOperateMode === 2
                                    ? 0
                                    : systemConfig.qty_show_precision
                                "
                                @change="
                                  changeLarge(
                                    $event,
                                    scope.row,
                                    `data.${scope.$index}.largeUnitQty`
                                  )
                                "
                                :min="0"
                                :max="largeMax(scope.row)"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div>
                          </div>
                          <div
                            class="page-table-input-number-item"
                            v-if="
                              scope.row.unitConvertCoefficient > 1 &&
                              scope.row.qtyOperateMode === 2
                            "
                          >
                            <el-form-item>
                              <el-input-number
                                style="width: 100%; margintop: 18px"
                                v-model.lazy="scope.row.smallUnitQty"
                                clearable
                                controls-position="right"
                                :precision="0"
                                :min="0"
                                :max="smallMax(scope.row)"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div>
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-right"
                          v-if="scope.row.qtyOperateMode === 2"
                        >
                          {{ $fn.qtyFormatter(scope.row.qty) }}
                        </div>
                      </div>
                    </el-form-item>
                    <span
                      v-else-if="
                        scope.row.codeType === 2 || scope.row.codeType === 3
                      "
                      >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                    >
                  </template>
                  <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                </template>
              </page-table>
            </el-form>
          </div>
          <!-- 选择部门 -->
          <select-dept
            v-if="deptInfo.visible"
            v-model:showDialog="deptInfo.visible"
            :query="deptInfo.query"
            @callback="selectDeptCallback"
            :checkBox="false"
            :highlightRow="true"
          />
          <!-- 选择部门 -->
          <select-dept
            v-if="sourceDeptInfo.visible"
            v-model:showDialog="sourceDeptInfo.visible"
            :query="sourceDeptInfo.query"
            @callback="selectSourceDeptCallback"
            :checkBox="false"
            :highlightRow="true"
          />
          <!-- 选择仓库 -->
          <SelectDepot
            v-if="depotInfo.visible"
            v-model:showDialog="depotInfo.visible"
            @callback="selectDepotCallback"
            :saveEmpty="true"
            :checkBox="false"
            :query="depotInfo.query"
            :highlightRow="true"
          />
          <!-- 选择产品 -->
          <SelectDepotStorage
            v-if="selectDepotStorageInfo.visible"
            v-model:showDialog="selectDepotStorageInfo.visible"
            :query="selectDepotStorageInfo.query"
            :excludeQueryList="selectDepotStorageInfo.excludeQueryList"
            :showPrice="$permission('useReturnApplication:price')"
            :leftTableKey="selectDepotStorageInfo.leftTableKey"
            :rightTableKey="selectDepotStorageInfo.rightTableKey"
            @callback="selectDepotStorageCallBack"
          />
        </div>
      </div>
    </NewFullScreen>
    <!-- 个体操作 -->
    <select-individual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      v-model:leftQueryObj="individualInfo.leftQuery"
      v-model:rightQueryObj="individualInfo.rightQuery"
      v-model:infoList="individualInfo.productInfo"
      :requestRightList="!!id"
      v-model:rightApi="individualInfo.rightApi"
      v-model:leftApi="individualInfo.leftApi"
      v-model:rightVo="individualInfo.rightVo"
      :showPrice="$permission('useAudit:price')"
      :scanInfo="scanInfo"
      :leftTableKey="individualInfo.leftTableKey"
      @callbackSacn="callbackSacn"
      @callback="selectedProductDetails"
    />
  </div>
</template>

<script setup name="useReturnApplicationModify">
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'
import {
  createUseReturnApplication,
  updateUseReturnApplication,
  getUseReturnApplicationDetailCustomizeList,
  getUseReturnApplication,
} from '@/api/use'
import {
  depotStockCustomizeScan,
  getDepotStockCustomizeListPage,
} from '@/api/stock'

import selectIndividual from '@/views/stock/components/individual'
import ScanInputBox from '@/views/stock/components/ScanInputBox'
import { getDepotPage } from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
const { proxy } = getCurrentInstance()
const emit = defineEmits()

const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))

const props = defineProps(['visible', 'title', 'id'])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const index = ref('')
const formRefs = ref([])
const formInfo = reactive({
  ref: null,
  data: {
    applicationUserName: proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.name
      : '',
    applicationUserId: proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.id
      : '',
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    storeDeptName: '',
    storeDeptId: '',
    storeDepotName: '',
    storeDepotId: '',
    depotName: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
        : ''
      : '',
    depotId: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
        : ''
      : '',
  },
  fieldList: [
    {
      label: '退回人',
      value: 'applicationUserName',
      type: 'input',
      disabled: true,
    },
    { label: '退出仓库', value: 'depotName', type: 'slot' },
    {
      label: '退回部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    { label: '退入仓库', value: 'storeDepotName', type: 'slot' },
    {
      label: '退入部门',
      value: 'storeDeptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'input',
      disabled: true,
      show:
        props.id &&
        proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    storeDepotName: [
      { required: true, message: '请选择退入仓库', trigger: 'change' },
    ],
    businessDate: [
      { required: true, message: '请选择业务日期', trigger: 'change' },
    ],
    depotName: [
      { required: true, message: '请选择退出仓库', trigger: 'change' },
    ],
    deptName: [{ required: true, message: '请输入退回部门', trigger: 'blur' }],
    storeDeptName: [
      { required: true, message: '请输入退入部门', trigger: 'blur' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'scanCode' },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  map: new Map(),
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '选择个体',
        event: _selectIndividual,
        show: true,
        ifRender: ifRenderValue,
      },
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
//选择库存产品
const selectDepotStorageInfo = reactive({
  //库存产品
  visible: false,
  excludeQueryList: [], //库存产品左侧过滤配置
  query: {
    depotId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
    generalProductCategory: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: 0,
    },
    isConsignBusiness: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: '',
    },
  },
  leftTableKey:
    'useReturnApplicationOrderModifyLeft-com.slip.spd.entity.vo.stock.DepotStockVO',
  rightTableKey:
    'useReturnApplicationOrderModifyRight-com.slip.spd.entity.vo.stock.DepotStockVO',
})
const scanInfo = reactive({
  api: depotStockCustomizeScan,
  query: {
    queryMap: {
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    customizeUserVO: {},
    queryParams: {
      depotId: proxy.$store.state.user.userInfo.coreResourcesVO
        ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
            '1'
          ) !== -1
          ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
          : ''
        : '',
      // validateExpire: false
    },
  },
})
const userInfo = reactive({
  visible: false,
})
const depotInfo = reactive({
  visible: false,
  depotType: '',
  query: {
    depotAuth: 'id',
    idNotIn: '',
    useTypeId: '1',
    status: '1',
  },
})
const deptInfo = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const sourceDeptInfo = reactive({
  visible: false,
  query: {
    status: '1',
  },
})
//个体操作相关
const individualInfo = reactive({
  visible: false,
  selectObj: {}, //库存产品弹窗左边后端合并项
  productInfo: {}, //个体操作的当前这条数据
  leftQuery: {}, //个体弹窗左边数据查询条件
  rightQuery: {}, //个体弹窗右边数据查询条件
  // rightApi: getUseReturnApplicationDetailCustomizeList, //个体弹窗右边数据接口
  leftApi: getDepotStockCustomizeListPage, //个体弹窗左边数据接口
  // leftApi: getUseReturnApplicationDetailCustomizeListPage, //个体弹窗左边数据接口
  rightApi: getUseReturnApplicationDetailCustomizeList, //个体弹窗右边数据接口
  rightVo: {}, //个体弹窗右边配置
  leftTableKey:
    'useReturnApplicationOrderModifyRight-com.slip.spd.entity.vo.stock.DepotStockVO',
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.data.filter((row) => row.productId && row.qty).length
})
const canDeleteProduct = computed(() => {
  return tableInfo.selections.length
})
const canAddProduct = computed(() => {
  return formInfo.data.deptId && formInfo.data.storeDeptId
})

watch(
  () => tableInfo.data,
  (val) => {
    if (val.length && !tableInfo.isSysGroup) {
      val.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.qtyFormatter(
          proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        )
        row['calcQty'] = calcQty
        row['qty'] = qty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )
        if (row.details && row.details.length) {
          row.details[0].qty = qty
          row.details[0].calcQty = calcQty
          row.details[0].largeUnitQty = largeUnitQty
          row.details[0].smallUnitQty = smallUnitQty
          row.details[0].sumAmount = row.sumAmount
        }
      })
    }
  },
  {
    deep: true,
  }
)

let obj = {
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    // type: 'slot',
    hidden: true,
  },
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useReturnApplication:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useReturnApplication:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('useReturnApplication:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
getInvdividualRightCustomize()

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  proxy.$nextTick(() => {
    if (!props.id) {
      formInfo.fieldList = formInfo.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})
let disStartDate = ref('')
let disEndDate = ref('')
setDisableTime(formInfo.fieldList, disStartDate, disEndDate)
async function setBusinessDate() {
  formInfo.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.stockAvailableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}

function ifRenderValue() {
  return tableInfo.isSysGroup
}
async function callbackSacn(data, oldInfo, callback) {
  //个体操作弹窗扫码回调
  let { mergeDetail, detail } = data
  mergeDetail[0].details = [detail]

  let key = []
  tableInfo.sysGroup.forEach((row) => {
    let obj = {}
    obj.columnName = row.columnName
    obj.asTbName = row.asTbName
    obj.value = mergeDetail[0][row.key]
    key.push(obj)
  })
  let newKey = JSON.stringify(key)
  if (tableInfo.map.has(newKey)) {
    if (
      oldInfo.groupConcatDepotStockIds.includes(detail.depotStockId.toString())
    ) {
      callback(true)
      return
    } else {
      if (oldInfo.key === newKey) {
        await setData(mergeDetail, newKey)
        await callback(false)
      } else {
        let value = tableInfo.map.get(newKey)
        if (
          await value.groupConcatDepotStockIds.includes(
            detail.depotStockId.toString()
          )
        ) {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          } else {
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          }
        } else {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(mergeDetail, newKey)
            await callback(false)
          } else {
            await setData(mergeDetail, newKey)
            await callback(false)
          }
        }
      }
    }
  } else {
    if ((await proxy.$fn.confirmRes()) === 'confirm') {
      await selectedProductDetails(oldInfo)
      await setData(mergeDetail, newKey)
      await callback(false)
    } else {
      await setData(mergeDetail, newKey)
      await callback(false)
    }
  }
}
async function _selectIndividual(data) {
  //选择个体
  await getIndividualInfoQuery(data)
  individualInfo.visible = true
}
async function getIndividualInfoQuery(data) {
  // 设置个体操作参数
  for (let key in individualInfo.selectObj) {
    individualInfo.selectObj[key].value = data[key]
  }
  individualInfo.leftQuery.id = {
    queryType: 'NOT_IN',
    queryCategory: 'AND',
    value: data.groupConcatDepotStockIds,
  }
  if (props.id) {
    individualInfo.leftQuery.isConsignBusiness = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: formInfo.data.isConsignBusiness,
    }
    individualInfo.rightQuery.isConsignBusiness = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: formInfo.data.isConsignBusiness,
    }
  }

  individualInfo.leftQuery.productId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: data.productId,
  }
  individualInfo.leftQuery.depotId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: formInfo.data.depotId,
  }
  individualInfo.leftQuery = {
    ...individualInfo.leftQuery,
    ...individualInfo.selectObj,
  }
  individualInfo.rightQuery.id = {
    queryType: 'IN',
    queryCategory: 'AND',
    value: data.groupConcatIds,
  }
  individualInfo.rightQuery.orderId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: props.id,
  }
  individualInfo.productInfo = data
}
async function selectedProductDetails(data) {
  //个体返回
  if (data.details && data.details.length) {
    tableInfo.map.set(data.key, data)
    let index = tableInfo.data.findIndex((item) => item.key === data.key)
    if (index !== -1) {
      tableInfo.data[index] = data
    }
  } else {
    removeProduct(data)
  }
}
async function setData(data, newKey, type = false) {
  //个体操作弹窗扫码回调设置数据

  let newData
  if (!type) {
    let map = await proxy.$fn.getDepotStorage(
      [data],
      tableInfo.sysGroup,
      tableInfo.map,
      getUseReturnApplicationDetailCustomizeList,
      props.id,
      individualInfo.rightVo,
      'scan'
    )
    tableInfo.map = map
    tableInfo.data = [...map.values()]
    newData = map.get(newKey)
  } else {
    newData = tableInfo.map.get(newKey)
  }
  await getIndividualInfoQuery(newData)
}
function getDeoptLeftCustomize() {
  //库存产品弹窗左侧配置

  let param = {
    tableKey:
      'useReturnApplicationOrderModifyLeft-com.slip.spd.entity.vo.stock.DepotStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      let obj = {}
      if (tableInfo.isSysGroup) {
        for (let key in data.detail) {
          if (data.detail[key].sysGroupLevel > 0) {
            arr.push({
              columnName: data.detail[key].columnName,
              asTbName: data.detail[key].asTbName,
              key: key,
            })
            obj[key] = {
              queryType: 'EQUALS',
              queryCategory: 'AND',
              ignoreEmptyValue: false,
              value: null,
            }
          }
        }
      } else {
        arr.push({
          columnName: data.detail.id.columnName,
          asTbName: data.detail.id.asTbName,
          key: 'depotStockId',
        })
        obj['depotStockId'] = {
          queryType: 'EQUALS',
          queryCategory: 'AND',
          value: null,
        }
      }
      scanInfo.query.customizeUserVO = data
      individualInfo.selectObj = obj
      tableInfo.sysGroup = arr
      if (props.id) {
        getMain()
      } else {
        setBusinessDate()
      }
    }
  })
}
function getInvdividualRightCustomize() {
  //获取个体弹窗右边配置;
  let param = {
    tableKey:
      'useReturnApplicationOrderModifySingle-com.slip.spd.entity.vo.use.UseReturnApplicationOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      individualInfo.rightVo = res.data
    }
  })
}
function getList() {
  //修改请求明细信息

  getUseReturnApplicationDetailCustomizeList(filterInfo.query).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      let data = resp.data
      data.forEach((item) => {
        //将返回的数据变成Map形式
        let key = []
        tableInfo.sysGroup.forEach((row) => {
          let obj = {}
          obj.columnName = row.columnName
          obj.asTbName = row.asTbName
          obj.value = item[row.key]
          key.push(obj)
        })
        item.key = JSON.stringify(key)
        tableInfo.map.set(item.key, item)
        if (!tableInfo.isSysGroup) {
          item.groupConcatDepotStockIds = item.depotStockId.toString()
          item.groupSize = 1
          let row = proxy.$fn.deepClone(item)
          delete row.key
          item.details = [row]
        }
        tableInfo.map.set(item.key, item)
      })
      tableInfo.data = data
    }
  })
}
function getMain() {
  getUseReturnApplication(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
      scanInfo.query.queryParams.depotId = resp.data.depotId
      scanInfo.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
    }
  })
  filterInfo.query.queryMap.orderId.value = props.id
  setBusinessDate()
  getList()
}
function getCustomize() {
  let param = {
    tableKey:
      'useReturnApplicationOrderModify-com.slip.spd.entity.vo.use.UseReturnApplicationOrderDetailVO',
  }
  tableInfo.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.isSysGroup = true
        }
      }
      filterInfo.query.customizeUserVO = data
      getDeoptLeftCustomize()
    }
  })
}
function generateProductKey(products) {
  return products.map((item) => {
    const key =
      item.productId +
      '&' +
      item.batchNumber +
      '&' +
      item.validityDate +
      '&' +
      item.productionDate
    item._id = key
    return item
  })
}
async function onCallBackScanData(data, callback) {
  //扫码回调
  let { mergeDetail, detail } = data

  if (tableInfo.data && tableInfo.data.length) {
    let items = tableInfo.data.filter((row) => {
      if (detail.codeType === 2 || detail.codeType === 3) {
        let arr = proxy.$fn.splitArr(row.groupConcatDepotStockIds)
        let bool = arr.includes(detail.depotStockId.toString())
        return bool
      } else if (detail.codeType === 1 || detail.codeType === 4) {
        if (row.id === mergeDetail[0].id) {
          let num = proxy.$fn.Subtr(row.stockAvailableCalcQty, row.calcQty)
          if (num <= 1) {
            return row.calcQty === row.stockAvailableCalcQty
          }
        }
      }
    })
    if (items.length) {
      callback(true)
      return
    } else {
      callback(false)
    }
  }
  mergeDetail[0].details = [detail]
  let map = await proxy.$fn.getDepotStorage(
    mergeDetail,
    tableInfo.sysGroup,
    tableInfo.map,
    getUseReturnApplicationDetailCustomizeList,
    props.id,
    individualInfo.rightVo
  )
  tableInfo.map = map
  tableInfo.data = [...map.values()]
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = data
      break
  }
}
//删除产品
function deleteProduct(data) {
  if (tableInfo.selections.length > 0) {
    tableInfo.data = tableInfo.data.filter(
      (row) => !tableInfo.selections.includes(row)
    )
  } else if (data && data.depotStockId) {
    tableInfo.data = tableInfo.data.filter((row) => data !== row)
  }
}
//选择库存产品
function addProduct() {
  let keys = [...tableInfo.map.keys()]
  let excludeQueryList = []
  if (keys.length && tableInfo.sysGroup.length) {
    excludeQueryList = keys.map((item) => JSON.parse(item))
  }
  selectDepotStorageInfo.excludeQueryList = excludeQueryList //库存产品左侧过滤配置
  selectDepotStorageInfo.query.depotId.value = formInfo.data.depotId
  if (props.id) {
    selectDepotStorageInfo.query.isConsignBusiness.value =
      formInfo.data.isConsignBusiness
  }
  selectDepotStorageInfo.visible = true
}
async function selectDepotStorageCallBack(rows = []) {
  //库存产品返回

  let map = await proxy.$fn.getDepotStorage(
    rows,
    tableInfo.sysGroup,
    tableInfo.map,
    getUseReturnApplicationDetailCustomizeList, //个体弹窗右边数据接口
    props.id,
    individualInfo.rightVo //个体弹窗右边表格配置
  )
  tableInfo.map = map
  tableInfo.data = [...map.values()]
}
//删除产品
function removeProduct(row = undefined) {
  if (row && row.key) {
    tableInfo.data = tableInfo.data.filter((item) => item.key !== row.key)
    let key = row.key
    tableInfo.map.delete(key)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.selections.forEach((row) => {
          for (let [key, value] of tableInfo.map) {
            if (key === row.key) {
              tableInfo.map.delete(key)
            }
          }
        })
        tableInfo.data = tableInfo.data.filter((row) => {
          return !tableInfo.selections.includes(row)
        })
        // tableInfo.data = tableInfo.data.filter(row => {
        //   for (let [key, value] of tableInfo.map) {
        //     if (key === row.key) {
        //       tableInfo.map.delete(key);
        //     }
        //   }
        //   return !tableInfo.selections.includes(row);
        // });
      })
  }
}
//填充库存产品
function fillStorageProduct(row = []) {
  row = generateProductKey(row)
  if (row.length) {
    tableInfo.data = tableInfo.data.concat(
      row.map((row) => {
        return {
          ...row,
          qty: 0,
          depotStockId: row.id,
          totalStockQty: row.stockQty,
          id: null, //这个id是库存的id，选择个体码的时候，会当成 明细id来处理
        }
      })
    )
  }
}
//选择领出仓库
function selectDepotExport() {
  depotInfo.depotType = 'export'
  depotInfo.query.idNot = formInfo.data.storeDepotId
  depotInfo.query.depotAuth = 'id'
  depotInfo.query.subDepotId = ''
  depotInfo.query.isCargoSpaceManage = 0
  depotInfo.visible = true
}
// 获取退出仓库
function getDepotExport() {
  if (formInfo.data.depotId) {
    depotInfo.query.depotAuth = ''
    depotInfo.query.subDepotId = formInfo.data.depotId
    let params = {
      sort: 'create_time desc',
      ...depotInfo.query,
      searchType: 'depot',
      useTypeId: '1',
      status: '1',
      curPage: 1,
      pageSize: 1,
    }
    getDepotPage(params).then((res) => {
      if (res && res.data.length) {
        let row = res.data[0]
        formInfo.data.storeDepotId = row.id
        formInfo.data.storeDepotName = row.name
        formInfo.data.storeDeptName = row.deptName ? row.deptName : ''
        formInfo.data.storeDeptId = row.deptId ? row.deptId : ''
      }
    })
  }
}
//选择领入仓库
function selectDepotStorage() {
  if (!formInfo.data.depotId) {
    proxy
      .$confirm('请选择退出仓库', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        selectDepotExport()
      })
    return
  }
  depotInfo.depotType = 'storage'
  depotInfo.query.isCargoSpaceManage = ''
  // depotInfo.query.idNot = formInfo.data.depotId;
  depotInfo.query.subDepotId = formInfo.data.depotId
  depotInfo.query.depotAuth = ''
  depotInfo.visible = true
}
function selectDepotCallback(row) {
  if (row) {
    if (depotInfo.depotType === 'export') {
      formInfo.data.depotId = row.id
      formInfo.data.depotName = row.name
      formInfo.data.deptName = row.deptName
      formInfo.data.deptId = row.deptId
      scanInfo.query.queryParams.depotId = row.id
      formInfo.data.storeDepotName = ''
      formInfo.data.storeDepotId = ''
      formInfo.data.storeDeptName = ''
      formInfo.data.storeDeptId = ''
      tableInfo.data = []
      tableInfo.map = new Map()
    } else if (depotInfo.depotType === 'storage') {
      formInfo.data.storeDepotId = row.id
      formInfo.data.storeDepotName = row.name
      formInfo.data.storeDeptName = row.deptName ? row.deptName : ''
      formInfo.data.storeDeptId = row.deptId ? row.deptId : ''
    }
  } else {
    if (depotInfo.depotType === 'export') {
      formInfo.data.depotId = ''
      formInfo.data.depotName = ''
      formInfo.data.deptName = ''
      formInfo.data.deptId = ''
      scanInfo.query.queryParams.depotId = ''
      formInfo.data.storeDepotName = ''
      formInfo.data.storeDepotId = ''
      formInfo.data.storeDeptName = ''
      formInfo.data.storeDeptId = ''
      tableInfo.data = []
      tableInfo.map = new Map()
    } else if (depotInfo.depotType === 'storage') {
      formInfo.data.storeDepotId = ''
      formInfo.data.storeDepotName = ''
      formInfo.data.storeDeptName = ''
      formInfo.data.storeDeptId = ''
    }
  }
}
//选择领用部门
function selectDept() {
  deptInfo.visible = true
  deptInfo.query.idNot = formInfo.data.storeDeptId
}
function selectDeptCallback(row) {
  if (row) {
    formInfo.data.deptName = row.name
    formInfo.data.deptId = row.id
    formInfo.data.depotName = formInfo.data.depotName
      ? formInfo.data.depotName
      : row.coreResourcesVO
      ? row.coreResourcesVO.resourceName
      : ''
    formInfo.data.depotId = formInfo.data.depotId
      ? formInfo.data.depotId
      : row.coreResourcesVO
      ? row.coreResourcesVO.resourceId
      : ''
    tableInfo.data = []
  }
}
//选择领用部门
function selectSourceDept() {
  sourceDeptInfo.visible = true
  sourceDeptInfo.query.idNot = formInfo.data.deptId
}
function selectSourceDeptCallback(row) {
  if (row) {
    formInfo.data.storeDeptName = row.name
    formInfo.data.storeDeptId = row.id
  }
}
//保存
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const data = formInfo.data
    const commonName = tableInfo.data
      .filter((row) => !row.qty || row.qty === 0)
      .map((item) => item.commonName)
    if (commonName.length) {
      proxy.$alert(`【${commonName}】的退回数量不能为0`, '操作提示', {
        confirmButtonText: '确定',
      })
      return
    }
    data.mergeDetails = proxy.$fn.filterBlacklist(tableInfo.data)
    data.type = 'useReturn'
    const api = data.id
      ? updateUseReturnApplication
      : createUseReturnApplication
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emit('returnModify')
      }
    })
  })
}
</script>

<style scoped>
.inputRefScanHidden {
  position: absolute;
  color: transparent;
  background-color: transparent;
  caret-color: black;
  border: none;
  outline: none;
  height: 30px;
  margin-left: 115px;
  width: 200px;
  z-index: 12;
}

.inputScan {
  ime-mode: disabled;
}

.active {
  display: none;
}
</style>
